import axios from 'axios'
import { Toast } from 'vant'
import store from '@/store/index.js'
import router from '../router'
import { getLocal, removeLocal } from '@/utils/local.js'
// 导入 jsonbigint
import jsonbig from 'json-bigint'
const _fetch = axios.create({
  baseURL: '/api',
  transformResponse: [
    // 将 超过 js 处理范围数字进行转换
    function (data) {
      try {
        // 就是服务器返回的 json 格式的字符串
        return jsonbig.parse(data)
      } catch {
        return JSON.parse(data)
      }
    }
  ]
})
const _ajax = function (obj) {
  return new Promise((resolve, reject) => {
    _fetch(obj)
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        window.console.log(err)
        // reject(err)
      })
  })
}
// 取消请求
let cancelArr = []
window.cancelAxios = function (url, allAxios = false) {
  cancelArr = cancelArr.filter(item => {
    if (allAxios) {
      item.c()
      return false
    } else {
      if (item.url === url) {
        item.c()
        return false
      } else {
        return true
      }
    }
  })
}
// 请求拦截器
_fetch.interceptors.request.use(
  function (config) {
    window.cancelAxios(config.url)
    config.cancelToken = new axios.CancelToken(cancel => {
      cancelArr.push({
        url: config.url,
        c: cancel
      })
    })
    if (config.needToken) {
      config.headers.authorization = `Bearer ${getLocal('token')}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
_fetch.interceptors.response.use(
  function (response) {
    if (
      response.status === 200 ||
      response.status === 201 ||
      response.status === 204
    ) {
      // 获取数据成功
      return response.data
    } else if (response.status === 401 || response.status === 403) {
      // token过期或用户未认证
      if (response.config.noError) {
        removeLocal('token')
        return Promise.reject(new Error('人为抛出错误,不用理会'))
      } else {
        // 删除token,跳转登录,设置vuex状态
        Toast.fail(response.data.message)
        removeLocal('token')
        router.push('/login')
        store.commit('setIsLogin', false)
        return Promise.reject(new Error('人为抛出错误,不用理会'))
      }
    } else {
      Toast.fail(response.data.message)
      return Promise.reject(new Error('人为抛出错误,不用理会'))
    }
  },
  function () {
    return Promise.reject(new Error('人为抛出错误,不用理会'))
  }
)
export default _ajax
